package com.woniuxy.gateway.handlder;

import com.woniuxy.gateway.entity.AuthUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.logout.ServerLogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * 登出接口,接口,准备做成黑白名单
 * LogoutHandler 即在程序执行logout时一起参与执行其中的处理逻辑，不能抛出异常，官方默认提供了几个实现。
 * <p>
 * PersistentTokenBasedRememberMeServices
 * TokenBasedRememberMeServices 移除Token
 * CookieClearingLogoutHandler 清楚Cookie
 * CsrfLogoutHandler 移除CSRF TOKEN
 * SecurityContextLogoutHandler
 * HeaderWriterLogoutHandler
 */
@Component
@Slf4j
public class SharedBatteryLogoutSuccessHandler implements ServerLogoutSuccessHandler {
    @Resource
    private StringRedisTemplate srt;

    @Override
    public Mono<Void> onLogoutSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        System.out.println("登出接口");
        AuthUserDetails utd = (AuthUserDetails) authentication.getPrincipal();
        //删除redis
        srt.opsForHash().delete("shared:battery:user:login", utd.getUserId() + "");
        ServerWebExchange exchange = webFilterExchange.getExchange();
        ServerHttpResponse response = exchange.getResponse();
        log.info(utd.getUserName() + "登出");
        DataBuffer wrap = response.bufferFactory().wrap((utd.getUserName() + "登出").getBytes());
        return response.writeWith(Mono.just(wrap));
    }
}
